package com.xiaodai.miaosha.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaodai.miaosha.entity.*;
import com.xiaodai.miaosha.mapper.OrdersMapper;
import com.xiaodai.miaosha.service.*;
import com.xiaodai.miaosha.utils.MD5Util;
import com.xiaodai.miaosha.utils.UUIDUtil;
import com.xiaodai.miaosha.vo.GoodsVo;
import com.xiaodai.miaosha.vo.OrderDeatilVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xiaodai
 * @since 2022-04-12
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements IOrdersService {
    @Resource
    private OrdersMapper orderMapper;
    @Autowired
    private ISeckillGoodsService seckillGoodsService;
    @Autowired
    private ISeckillOrderService seckillOrderService;
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private IAddressService addressService;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Long getResult(Msuser msuser, Long goodsId, String addressId) {
        System.out.println(msuser.getId());
        System.out.println(goodsId);
        System.out.println(addressId);

        Orders order = orderMapper.selectOne(new QueryWrapper<Orders>().eq("user_id",msuser.getId()).eq("goods_id",goodsId).eq("delivery_addr_id",addressId));
        if (order != null){
            return order.getId();
        }else if (redisTemplate.hasKey("isStockEmpty:"+goodsId)){
            return -1L;
        }else {
            return 0L;
        }
    }

    @Override
    @Transactional
    public Orders seckill(Msuser Msuser, GoodsVo goods,String addressId) {
        ValueOperations valueOperations = redisTemplate.opsForValue();
        SeckillGoods seckillGoods = seckillGoodsService.getOne(new QueryWrapper<SeckillGoods>().eq("goods_id", goods.getId()));
        seckillGoods.setStockCount(seckillGoods.getStockCount() - 1);
        seckillGoodsService.update(new UpdateWrapper<SeckillGoods>().eq("goods_id", goods.getId()).set("stock_count", seckillGoods.getStockCount()).gt("stock_count", 0));
        boolean seckillGoodsResult = seckillGoodsService.update(new UpdateWrapper<SeckillGoods>()
                .setSql("stock_count = " + "stock_count-1")
                .eq("goods_id", goods.getId())
                .gt("stock_count", 0)
        );
        if (!seckillGoodsResult) {
            return null;
        }
        if (seckillGoods.getStockCount() < 1) {
            valueOperations.set("isStockEmpty:" + goods.getId(), "0");
            return null;
        }
        Orders order = new Orders();
        order.setUserId(String.valueOf(Msuser.getId()));
        order.setGoodsId(goods.getId());
        order.setDeliveryAddrId(null);
        order.setGoodsName(goods.getGoodsName());
        order.setDeliveryAddrId(addressId);
        order.setGoodsCount(1);
        order.setGoodsPrice(seckillGoods.getSeckillPrice());
        order.setOrderChannel(1);
        order.setStatus(0);
        order.setCreateDate(new Date());
        orderMapper.insert(order);
        //生成秒杀订单
        SeckillOrder seckillOrder = new SeckillOrder();
        seckillOrder.setOrderId(order.getId());
        seckillOrder.setGoodsId(goods.getId());
        seckillOrder.setUserId(Msuser.getId());
        seckillOrderService.save(seckillOrder);

        valueOperations.set("order:" + Msuser.getId() + ":" + goods.getId(), seckillOrder);
        return order;
    }

    @Override
    public OrderDeatilVo detail(Long orderId) {
        if (orderId == null) {
            return null;
        }
        OrderDeatilVo orderDeatilVo = new OrderDeatilVo();
        Orders order = orderMapper.selectById(orderId);
        GoodsVo goodsVo = goodsService.findGoodsVoById(order.getGoodsId());
        Address address = addressService.getById(order.getDeliveryAddrId());
        orderDeatilVo.setOrder(order);
        orderDeatilVo.setGoodsVo(goodsVo);
        orderDeatilVo.setAddress(address);

        return orderDeatilVo;
    }

    @Override
    public String getPath(Msuser Msuser, Long goodsId) {
        String str = MD5Util.md5(UUIDUtil.uuid() + "123456");
        redisTemplate.opsForValue().set("seckillPath:" + Msuser.getId() + ":" + goodsId, str, 1, TimeUnit.MINUTES);
        return str;
    }

    @Override
    public Boolean checkPath(Msuser Msuser, Long goodsId, String path) {
        if (Msuser == null || goodsId < 0 || StringUtils.isEmpty(path)) {
            return false;
        }
        String str = (String) redisTemplate.opsForValue().get("seckillPath:" + Msuser.getId() + ":" + goodsId);
        return path.equals(str);
    }

    @Override
    public Boolean checkCaptcha(Msuser Msuser, Long goodsId, String captcha) {
        if (Msuser == null || goodsId < 0 || StringUtils.isEmpty(captcha)) {
            return false;
        }
        String cap = (String)redisTemplate.opsForValue().get("captcha:" + Msuser.getId() + ":" + goodsId);
        return captcha.equals(cap);
    }
}
